<template>
  <div class="my-dialog">
    <vxe-modal
      show-footer
      show-confirm-button
      show-cancel-button
      show-zoom
      title="显隐控制"
      resize
      :lock-view="false"
      :mask="false"
      v-model="visible"
      confirm-button-text="自定义确认"
      cancel-button-text="自定义取消"
      :width="340"
      :height="400"
      @close="handleClose"
      size="small"
      :position="{
        top: 40,
        left: 15,
      }"
    >
      <el-checkbox-group v-model="visibleList" @change="hanleCheckChange">
        <el-checkbox label="范围雷达"></el-checkbox>
        <el-checkbox label="雷达探测线"></el-checkbox>
      </el-checkbox-group>
      <el-form
        ref="form"
        :model="camberRadarForm"
        label-width="140px"
        size="mini"
        label-position="left"
      >
        <el-form-item label="范围雷达颜色">
          <el-color-picker
            v-model="camberRadarForm.color"
            @change="camberRadarColorChange"
          ></el-color-picker>
        </el-form-item>
        <el-form-item label="范围雷达线框颜色">
          <el-color-picker
            v-model="camberRadarForm.lineColor"
            @change="camberRadarLineColorChange"
          ></el-color-picker>
        </el-form-item>
        <el-form-item label="范围雷达内部半径">
          <el-input-number
            v-model="camberRadarForm.startRadius"
            @change="handleStartRadius"
          ></el-input-number>
        </el-form-item>
        <el-form-item label="范围雷达外部半径">
          <el-input-number
            v-model="camberRadarForm.radius"
            @change="handleRadius"
          ></el-input-number>
        </el-form-item>
        <el-form-item label="范围雷达水平张角">
          <el-input-number
            v-model="camberRadarForm.endFovH"
            @change="handleEndFovH"
          ></el-input-number>
        </el-form-item>
        <el-form-item label="范围雷达竖直张角">
          <el-input-number
            v-model="camberRadarForm.endFovV"
            @change="handleEndFovV"
          ></el-input-number>
        </el-form-item>
      </el-form>

      <v-stage :config="configKonva">
        <v-layer>
          <v-circle :config="configCircle"></v-circle>
        </v-layer>
      </v-stage>

      <div>
        <uploader
          ref="uploader"
          :options="options"
          :autoStart="false"
          :file-status-text="fileStatusText"
          @file-added="onFileAdded"
          @file-success="onFileSuccess"
          @file-removed="filesRemove"
          @file-error="onFileError"
          class="uploader-ui"
        >
          <uploader-unsupport></uploader-unsupport>
          <uploader-drop>
            <div>
              <uploader-btn id="global-uploader-btn" ref="uploadBtn">
                选择文件
                <i class="el-icon-upload el-icon--right"></i>
              </uploader-btn>
            </div>
          </uploader-drop>
          <uploader-list></uploader-list>
        </uploader>
      </div>
    </vxe-modal>
  </div>
</template>

<script>
import texture from "@/assets/images/texture/glow.png";
export default {
  name: "VisibleControl",
  data() {
    return {
      visible: false,
      visibleList: ["范围雷达", "雷达探测线"],
      camberRadarForm: {
        color: "#fff000",
        lineColor: "#ffffff",
        startRadius: 1000, //内曲面半径
        radius: 3000, //外曲面半径
        endFovH: 270, //右横截面角度，结束角度
        endFovV: 90, //垂直方向张角，结束角度
      },
      configKonva: {
        width: 200,
        height: 200,
      },
      configCircle: {
        x: 100,
        y: 100,
        radius: 70,
        fill: "red",
        stroke: "black",
        strokeWidth: 4,
      },
      options: {
        //目标上传 URL，默认POST
        target: process.env.VUE_APP_BASE_URL + "/uploader/chunk",
        //分块大小(单位：字节)
        chunkSize: "2048000",
        //上传文件时文件内容的参数名，对应chunk里的Multipart对象名，默认对象名为file
        fileParameterName: "upfile",
        //失败后最多自动重试上传次数
        maxChunkRetries: 3,
        changeOrigin: true,
        //是否开启服务器分片校验，对应GET类型同名的target URL
        testChunks: true,
        headers: { Authorization: "Bearer " + localStorage.getItem("token") },
        /*
                 服务器分片校验函数，判断秒传及断点续传,传入的参数是Uploader.Chunk实例以及请求响应信息
                 reponse码是successStatuses码时，才会进入该方法
                 reponse码如果返回的是permanentErrors 中的状态码，不会进入该方法，直接进入onFileError函数 ，并显示上传失败
                 reponse码是其他状态码，不会进入该方法，正常走标准上传
                 checkChunkUploadedByResponse函数直接return true的话，不再调用上传接口
                 */
        checkChunkUploadedByResponse: function (chunk, response_msg) {
          let objMessage = JSON.parse(response_msg);
          if (objMessage.skipUpload) {
            return true;
          }
          return (
            (objMessage.uploadedChunks || []).indexOf(chunk.offset + 1) >= 0
          );
        },
      },
      fileStatusText: {
        success: "上传成功",
        error: "上传失败",
        uploading: "上传中",
        paused: "暂停",
        waiting: "等待上传",
      },
    };
  },
  mounted() {},
  methods: {
    open() {
      this.visible = true;
      window.vis3d.util.setCameraView(
        {
          x: 117.25909590820321,
          y: 31.932288340987522,
          z: 10502.008632373832,
          heading: 279.69000256485947,
          pitch: -42.53749481358753,
          roll: 359.99528816493176,
          duration: 3,
        },
        window.viewer
      );
      this.handleCamberRadar();
      this.handleFlowLine();
    },
    handleClose() {
      this.visible = false;
      this.$emit("menuClose", "visibleControlRef");
    },
    // 添加范围雷达
    handleCamberRadar() {
      let position = Cesium.Cartesian3.fromDegrees(117.141, 31.95, 100);
      let modelMatrix = this.createModelMatrix(position, 0, 0, 0);
      let primitive = window.viewer.scene.primitives.add(
        new window.vis3d.sensor.CamberRadarPrimitive({
          modelMatrix: modelMatrix,
          color: Cesium.Color.fromCssColorString(
            this.camberRadarForm.color
          ).withAlpha(0.5),
          lineColor: Cesium.Color.fromCssColorString(
            this.camberRadarForm.lineColor
          ),
          startRadius: this.camberRadarForm.startRadius, //内曲面半径
          radius: this.camberRadarForm.radius, //外曲面半径
          startFovH: Cesium.Math.toRadians(0), //左横截面角度，起始角度
          endFovH: Cesium.Math.toRadians(this.camberRadarForm.endFovH), //右横截面角度，结束角度
          startFovV: Cesium.Math.toRadians(0), //垂直方向张角，起始角度
          endFovV: Cesium.Math.toRadians(this.camberRadarForm.endFovV), //垂直方向张角，结束角度
          segmentH: 10, //Math.abs(item.endFovH - item.startFovH)/20,
          segmentV: 20,
          subSegmentH: 3,
          subSegmentV: 5,
          show: true,
        })
      );
      primitive.customName = "范围雷达";
    },
    // 创建模型矩阵
    createModelMatrix(position, heading, pitch, roll, scale, result) {
      scale = scale || 1;
      var enuMatrix = Cesium.Transforms.eastNorthUpToFixedFrame(
        position,
        undefined,
        result
      );
      var scaleMatrix = Cesium.Matrix4.fromScale(
        new Cesium.Cartesian3(scale, scale, scale),
        new Cesium.Matrix4()
      );
      var modelMatrix = Cesium.Matrix4.multiply(
        enuMatrix,
        scaleMatrix,
        enuMatrix
      );
      var rotateMatrix = Cesium.Matrix3.fromHeadingPitchRoll(
        Cesium.HeadingPitchRoll.fromDegrees(heading, pitch, roll),
        new Cesium.Matrix3()
      );
      return Cesium.Matrix4.multiplyByMatrix3(
        modelMatrix,
        rotateMatrix,
        modelMatrix
      );
    },
    hanleCheckChange() {
      if (this.visibleList.some((item) => item == "范围雷达")) {
        window.viewer.scene.primitives._primitives.find(
          (item) => item.customName == "范围雷达"
        ).show = true;
      } else {
        window.viewer.scene.primitives._primitives.find(
          (item) => item.customName == "范围雷达"
        ).show = false;
      }
      if (this.visibleList.some((item) => item == "雷达探测线")) {
        window.viewer.entities.values.find(
          (item) => item.customName == "雷达探测线"
        ).show = true;
      } else {
        window.viewer.entities.values.find(
          (item) => item.customName == "雷达探测线"
        ).show = false;
      }
    },
    // 范围雷达颜色
    camberRadarColorChange(val) {
      window.viewer.scene.primitives._primitives.find(
        (item) => item.customName == "范围雷达"
      ).color = new Cesium.Color.fromCssColorString(val);
    },
    // 范围雷达线颜色
    camberRadarLineColorChange(val) {
      window.viewer.scene.primitives._primitives.find(
        (item) => item.customName == "范围雷达"
      ).lineColor = new Cesium.Color.fromCssColorString(val);
    },
    // 范围雷达内部半径
    handleStartRadius(val) {
      window.viewer.scene.primitives._primitives.find(
        (item) => item.customName == "范围雷达"
      ).startRadius = val;
    },
    // 范围雷达外部半径
    handleRadius(val) {
      window.viewer.scene.primitives._primitives.find(
        (item) => item.customName == "范围雷达"
      ).radius = val;
    },
    // 范围雷达水平张角
    handleEndFovH(val) {
      window.viewer.scene.primitives._primitives.find(
        (item) => item.customName == "范围雷达"
      ).endFovH = Cesium.Math.toRadians(val);
    },
    // 范围雷达垂直
    handleEndFovV(val) {
      window.viewer.scene.primitives._primitives.find(
        (item) => item.customName == "范围雷达"
      ).endFovV = Cesium.Math.toRadians(val);
    },
    handleFlowLine() {
      // 雷达探测线
      let ent = window.viewer.entities.add({
        polyline: {
          positions: Cesium.Cartesian3.fromDegreesArray([
            117.25909590820321, 31.932288340987522, 117.05909590820321, 32,
          ]),
          width: 3,
          material: new window.vis3d.material.LineFlow({
            color: Cesium.Color.YELLOW,
            duration: 3000,
            image: texture,
            repeat: new Cesium.Cartesian2(1, 1), //平铺
          }),
        },
      });
      ent.customName = "雷达探测线";
    },
    onFileAdded(file) {
      this.computeMD5(file);
    },
    /*
         第一个参数 rootFile 就是成功上传的文件所属的根 Uploader.File 对象，它应该包含或者等于成功上传文件；
         第二个参数 file 就是当前成功的 Uploader.File 对象本身；
         第三个参数就是 message 就是服务端响应内容，永远都是字符串；
         第四个参数 chunk 就是 Uploader.Chunk 实例，它就是该文件的最后一个块实例，如果你想得到请求响应码的话，chunk.xhr.status就是
         */
    onFileSuccess(rootFile, file, response, chunk) {
      //refProjectId为预留字段，可关联附件所属目标，例如所属档案，所属工程等
      file.refProjectId = "123456789";
      console.log("::::", file);
      let data = file;
      data.filename = file.name;
      data.identifier = file.uniqueIdentifier;
      data.totalSize = file.size;
      data.alluxioPath = this.sendContent.alluxioPath;
      data.userStorageId = this.sendContent.id;
      console.log("file", file, data);

      mergeFile(data).then((res) => {
        console.log("23342", res);
        console.log("父组件", this.$parent);
        // if (res.code === 415) {
        //     console.log('合并操作未成功，结果码：' + res.code);
        // }
        if (res.code == 200) {
          if (this.sendContent.idArray && this.sendContent.idArray.length > 0) {
            this.sendContent.idArray.forEach((item) => {
              // this.$parent.refreshList(item)
              console.log("aaaaaaaaa", item);
              this.$emit("refresh", item);
              this.$emit("getFather");
            });
            this.$message.success(res.message);
          }
        } else {
          this.$message.error(res.message);
        }
      });
      // .catch(function (error) {
      //     console.log('合并后捕获的未知异常：' + error);
      // });
    },

    filesRemove(file) {
      // this.$refs.uploader.pause();
      file.paused = true;
      let data = file;
      data.filename = file.name;
      data.identifier = file.uniqueIdentifier;
      data.totalSize = file.size;
      data.alluxioPath = this.sendContent.alluxioPath;
      data.userStorageId = this.sendContent.id;
      deleteMkFile(data).then((res) => {
        console.log("delete", res);
        if (res.code == 200) {
          this.$message.success(res.msg);
        } else {
          this.$message.error(res.msg);
        }
      });
      // const uploaderInstance = this.$refs.uploader.uploader;
      // let temp = uploaderInstance.fileList.findIndex(e => e.uniqueIdentifier === file.uniqueIdentifier)
      // if (temp > -1) {
      //     uploaderInstance.fileList[temp].cancel();   //这句代码是删除所选上传文件的关键
      // }
    },

    onFileError(rootFile, file, response, chunk) {
      console.log("上传完成后异常信息：" + response);
    },
    onFileProgress(rootFile, file, chunk) {
      console.log(
        `上传中 ${file.name}，chunk：${chunk.startByte / 1024 / 1024} ~ ${
          chunk.endByte / 1024 / 1024
        }`
      );
    },
    /**
     * 计算md5，实现断点续传及秒传
     * @param file
     */
    computeMD5(file) {
      file.pause();

      //单个文件的大小限制2G
      let fileSizeLimit = 2 * 1024 * 1024 * 1024;
      console.log("文件大小：" + file.size);
      console.log("限制大小：" + fileSizeLimit);
      console.log("alluxioPath" + this.sendContent.alluxioPath);
      // if (file.size > fileSizeLimit) {
      //     this.$message({
      //         showClose: true,
      //         message: '文件大小不能超过2G'
      //     });
      //     file.cancel();
      // }

      let fileReader = new FileReader();
      let time = new Date().getTime();
      let blobSlice =
        File.prototype.slice ||
        File.prototype.mozSlice ||
        File.prototype.webkitSlice;
      let currentChunk = 0;
      const chunkSize = 10 * 1024 * 1000;
      let chunks = Math.ceil(file.size / chunkSize);
      let spark = new SparkMD5.ArrayBuffer();
      //由于计算整个文件的Md5太慢，因此采用只计算第1块文件的md5的方式
      let chunkNumberMD5 = 1;

      loadNext();

      fileReader.onload = (e) => {
        spark.append(e.target.result);

        if (currentChunk < chunkNumberMD5) {
          loadNext();
        } else {
          let md5 = spark.end();
          file.uniqueIdentifier = md5;
          file.resume();
          console.log(
            `MD5计算完毕：${file.name} \nMD5：${md5} \n分片：${chunks} 大小:${
              file.size
            } 用时：${new Date().getTime() - time} ms`
          );
        }
      };

      fileReader.onerror = function () {
        this.error(`文件${file.name} 读取出错，请检查该文件`);
        file.cancel();
      };

      function loadNext() {
        let start = currentChunk * chunkSize;
        let end =
          start + chunkSize >= file.size ? file.size : start + chunkSize;

        fileReader.readAsArrayBuffer(blobSlice.call(file.file, start, end));
        currentChunk++;
        console.log("计算第" + currentChunk + "块");
      }
    },
    error(msg) {
      this.$notify({
        title: "错误",
        message: msg,
        type: "error",
        duration: 2000,
      });
    },
  },
};
</script>

<style scoped lang="scss">
::v-deep .el-form {
  .el-form-item {
    margin-bottom: 10px;
  }
}
</style>
